package com.github.baichuan.gb32960.codec;

import com.github.baichuan.gb32960.utils.ByteBufHelper;
import com.github.baichuan.iot.protocol.pdu.Decoder;
import io.netty.buffer.ByteBuf;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 整车数据
 */
public class Vehicle implements Decoder {
    @Override
    public List<Map<String, Object>> decode(ByteBuf buf) {
        byte[] word = new byte[2];

        Map<String, Object> data = new TreeMap<>();

        // 车辆状态
        data.put("vehicleStatus", buf.readUnsignedByte());

        // 充电状态
        data.put("chargeStatus", buf.readUnsignedByte());

        // 运行模式
        data.put("runStatus", buf.readUnsignedByte());

        // 车速
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("speed", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
        });

        // 累计里程
        ByteBufHelper.readUnsignedInt(buf).ifPresent(value -> {
            data.put("odo", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
        });

        // 总电压
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("voltage", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
        });

        // 总电流
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("current", BigDecimal.valueOf((value * 0.1) - 1000).setScale(1, RoundingMode.HALF_UP));
        });

        // SOC
        data.put("soc", buf.readUnsignedByte());

        // DC-DC状态
        data.put("dcdc", buf.readUnsignedByte());

        // 挡位
        data.put("gear", buf.readUnsignedByte());

        // 绝缘电阻
        data.put("resistor", buf.readUnsignedShort());

        // 预留
        buf.skipBytes(2);

        return Arrays.asList(data);
    }
}
